package com.sniff.atp.modules.test.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ckbs.user.client.dto.resp.ManageLoginRespDTO;
import com.ckbs.user.client.utils.JwtUtil;
import com.sniff.atp.common.api.CommonResult;
import com.sniff.atp.constant.RedisPrefix;
import com.sniff.atp.manage.RedisManage;
import com.sniff.atp.utils.HttpClientUtil;
import com.sniff.atp.utils.JsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @BelongsProject: sniff-atp
 * @BelongsPackage: com.sniff.atp.modules.test.controller
 * @Author: zxy
 * @CreateTime: 2023-12-12 13:54
 * @Description: sldfasldf
 * @Version: 1.0
 */
@RestController
@RequestMapping("/ops")
@Api(value = "ops模块", tags = "ops模块")
@Slf4j
public class OpsUserController {
    @Autowired
    private RedisManage redisManage;

    @PostMapping("/logOut")
    public Object test(){
        return CommonResult.failed("login out");
    }

    @GetMapping("/err")
    public Object userErr(){

        return CommonResult.success("{\"code\": \"24000001\",\"msg\":\"token为空\"}");
    }

    @PostMapping("/login")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "String",name = "username",value = "用户名",required = true),
            @ApiImplicitParam(paramType = "String",name = "password",value = "密码",required = true)})
    public Object login(@RequestParam String username, @RequestParam String password){

        HashMap<String, Object> params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);

        String result = "";
        try {
            result = new HttpClientUtil().doPost("https://gateway-prod.theckb.com/customer/users/token", params);
        }catch ( AssertionError e) {

            log.info("{}", e.getMessage());
            String s = e.getMessage();
            String expecteds = s.split("expected")[0];

            return JsonUtil.strToJSONObject(expecteds);
        }

        String token = JsonUtil.extractString(result, "data.token");
        if(token == null){
            return CommonResult.failed("登录失败");
        }
        ManageLoginRespDTO manageDTO = JwtUtil.getManageDTO(token);
        redisManage.setKey(RedisPrefix.SNIFF_USER_TOKEN + manageDTO.getUserId(), token, (long)(24*60*60));

        JSONObject jsonObject = JsonUtil.extractJSONObject(result, "data");

        return CommonResult.success(jsonObject);
    }
}
